package match

import (
)

// 匹配中的玩家信息
// 当多名玩家组队进来匹配时，应该要把这多名玩家看成整体来对待
type MatchPlayer struct {
	// PlayerId 	int32 	// 玩家 id
	PlayerIds 	[]int32 // 玩家 id 列表
	Rating 		int32 	// 玩家的匹配积分
	Wait		float64	// 等待时间，秒
	RoomDis		int32 	// 能够跨房间匹配的房间 id 距离，0表示只会匹配本房间

	Num 		int 	// 当前队伍中的人数

	Team 		*MatchTeam 	// 玩家所在的匹配队伍
}

// 创建匹配玩家信息，id, rating, id, rating ...
func NewMatchPlayer(infos... int32) *MatchPlayer {
	p := &MatchPlayer{}
	var rating int32
	for i := 0 ; i < len(infos) - 1; i += 2 {
		p.PlayerIds = append(p.PlayerIds, infos[i])
		rating += infos[i+1]
	}
	if len(p.PlayerIds) > 0 {
		p.Rating = rating / int32(len(p.PlayerIds))
		// p.PlayerId = p.PlayerIds[0]
	}
	p.Wait = 0
	p.RoomDis = 0
	p.Num = len(p.PlayerIds)
	return p
}

// 匹配组成的队伍
type MatchTeam struct {
	Players		[]*MatchPlayer 	// 组成队伍的玩家列表
	TotalRating	int32 	// 总积分
	Rating 		int32 	// 玩家的匹配积分
	Wait		float64	// 等待时间，秒
	RoomDis		int32 	// 能够跨房间匹配的房间 id 距离，0表示只会匹配本房间

	Num 		int 	// 当前队伍中的人数
	NumLimit	int 	// 队伍人数
}

func NewMatchTeam(numLimit int) *MatchTeam {
	t := &MatchTeam{}
	t.NumLimit = numLimit
	return t
}

func (t *MatchTeam) IsEmpty() bool {
	return t.Num <= 0
}

func (t *MatchTeam) IsFull() bool {
	return t.Num == t.NumLimit
}

func (t *MatchTeam) GetPlayerIds() []int32 {
	ids := make([]int32, 0, t.Num)
	for _, p := range t.Players {
		ids = append(ids, p.PlayerIds...)
	}
	return ids
}

// 添加玩家，如果玩家已经有队伍了或加入后队伍人数超过上限，则添加失败
func (t *MatchTeam) AddPlayer(p *MatchPlayer) bool {
	if nil != p.Team {
		return false
	}
	if t.Num + p.Num > t.NumLimit {
		return false
	}

	t.Players = append(t.Players, p)
	p.Team = t
	t.Num += p.Num
	t.TotalRating += p.Rating
	if len(t.Players) > 0 {
		t.Rating = t.TotalRating / int32(len(t.Players))
	} else {
		t.Rating = 0
	}
	return true
}

// 离开匹配队伍
func (t *MatchTeam) RemovePlayer(p *MatchPlayer) {
	for k, v := range t.Players {
		if v == p {
			t.Players = append(t.Players[:k], t.Players[k+1:]...)
			t.Num -= p.Num
			p.Team = nil
			t.TotalRating -= p.Rating
			if len(t.Players) > 0 {
				t.Rating = t.TotalRating / int32(len(t.Players))
			} else {
				t.Rating = 0
			}
			break
		}
	}
}

// 尝试合并队伍，使自己满员
func (t *MatchTeam) MergeTeam(other *MatchTeam) bool {
	flag := false
	for i := 0; i < len(other.Players); {
		p := other.Players[i]
		if t.Num + p.Num <= t.NumLimit {
			other.Players = append(other.Players[:i], other.Players[i+1:]...)
			p.Team = nil
			other.Num -= p.Num
			other.TotalRating -= p.Rating
			t.AddPlayer(p)
			flag = true
		} else {
			i++
		}
	}

	if flag {
		if len(other.Players) > 0 {
			other.Rating = other.TotalRating / int32(len(other.Players))
		} else {
			other.Rating = 0
		}
	}
	return flag
}
